import crypto, { Cipher, Decipher } from 'crypto';
import { cryptoConfig } from '../config/app.config';
import bcrypto from 'bcryptjs';

/**原生写法******************************************************************************************/

/**
 * 加密方法
 * @param key  加密的key
 * @param iv   向量
 * @param data 需要加密的数据
 * @deprecated
 */
function encrypt(data: string): string {
  const cipher: Cipher = crypto.createCipheriv(cryptoConfig.algorithm, cryptoConfig.key, cryptoConfig.iv);
  let crypted: string = cipher.update(data, 'utf8', 'hex');
  crypted += cipher.final('hex');
  crypted = Buffer.from(crypted, 'hex').toString('base64');
  return crypted;
}

/**
 * 解密方法
 * @deprecated
 */
function decrypt(data: string): string {
  const crypted: string = Buffer.from(data, 'base64').toString('hex');
  const decipher: Decipher = crypto.createDecipheriv(cryptoConfig.algorithm, cryptoConfig.key, cryptoConfig.iv);
  let decode: string = decipher.update(crypted, 'hex', 'utf8');
  decode += decipher.final('utf8');
  return decode;
}

export const ocrypt = { encrypt, decrypt };

/**三方写法******************************************************************************************/

/**
 * 加密方法
 * @param s 原始数据
 */
function hash(s: string) {
  const salt = bcrypto.genSaltSync();
  return bcrypto.hashSync(s, salt);
}

/**
 * 验证方法
 * @param s 原始数据
 * @param hash 加密后的数据
 */
function compare(s: string, hash: string) {
  return bcrypto.compareSync(s, hash);
}

/**
 * 获取盐
 * @param hash 加密后的数据
 */
function getSalt(hash: string) {
  return bcrypto.getSalt(hash);
}

export const bcrypt = { hash, compare, getSalt };
